import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.util.List;


public class MouseReaction {
    private double SPRINGINESS = 0.3;
    private double mySpringLength;
    private Mass myClosestMass;
    private Mass myMouseMass;
    private Spring mySpringToMouse;
    private Point myLastMousePosition;

    public MouseReaction(Canvas container,Simulation sim,Point LastMousePosition){
        List<Mass> masses = sim.getMassList();
        myLastMousePosition = LastMousePosition;
        myClosestMass = getClosest(masses,myLastMousePosition);
        myMouseMass = new Mass((Integer) 0,myLastMousePosition.x,myLastMousePosition.y,0);
        mySpringToMouse = new Spring(myMouseMass,myClosestMass,mySpringLength,SPRINGINESS);
    }
    public void update(Point lastMousePosition){
        myLastMousePosition = lastMousePosition;
        myMouseMass.setCenter(myLastMousePosition.x, myLastMousePosition.y);
        Force springForce = mySpringToMouse.getSpringForce();
        springForce.negate();
        myClosestMass.applyForce(springForce);
    }
    
    public void paint(Graphics2D pen){
        myClosestMass.paint(pen);
        mySpringToMouse.paint(pen);
        myMouseMass.paint(pen);
    }
    private Mass getClosest(List<Mass> masses,Point location){
        double closestDist = 10000000;
        Mass closestMass = null;
        for(Mass m:masses){
            double dist = getDistance(location, m);
            if(dist<closestDist){
                closestDist = dist;
                closestMass = m;
            }
        }
        mySpringLength = closestDist;
        return closestMass;
    }
    private double getDistance (Point location, Mass m) {
        double massX = m.getCenter().getX();
        double massY = m.getCenter().getY();
        double locX = location.getX();
        double locY = location.getY();
        double dist = Point.distance(massX, massY, locX, locY);
        return dist;
    }
}
